from odoo import api, fields, models


def fulfill_name(last_name, first_name):
    return last_name + ' ' + first_name


class ResPartnerInheritForBasic(models.Model):
    _inherit = 'res.partner'

    company_type = fields.Selection(store=True)

    first_name = fields.Char(string='名')
    last_name = fields.Char(string='姓')

    fax = fields.Char(string='传真')

    location_lng = fields.Char(string='经度')
    location_lat = fields.Char(string='纬度')

    postal_code_id = fields.Many2one(string='邮编', comodel_name='res.postal.code')
    city_id = fields.Many2one(string='城市', comodel_name='res.city')
    county_id = fields.Many2one(string='区/县', comodel_name='res.county')

    address_str = fields.Char(string='地址char', compute='_depends_fulfill_address_str', store=True)

    @api.onchange('first_name', 'last_name')
    def _onchange_fill_name(self):
        if self.company_type == 'person':
            if self.first_name and self.last_name:
                self.update({'name': fulfill_name(self.last_name, self.first_name)})

    @api.onchange('company_type')
    def _onchange_company_type(self):
        if self.company_type == 'person':
            self.update({'name': False})
        elif self.company_type == 'company':
            self.update({'first_name': False, 'last_name': False})

    """ 国家-省-市-区-街道 数据联动 """

    # 1、原函数覆盖
    @api.onchange('state_id')
    def _onchange_state(self):
        if self.city_id and self.state_id != self.city_id.state_id:
            self.city_id = False
        self.street = False

    # 2、新增市级、区级
    @api.onchange('city_id')
    def _onchange_city(self):
        if self.county_id and self.city_id != self.county_id.city_id:
            self.county_id = False
        self.street = False

    @api.onchange('county_id')
    def _onchange_county(self):
        self.street = False

    @api.onchange('country_id', 'state_id', 'city_id', 'county_id')
    def _onchange_address(self):
        """ 通过“国家省市区”获取“邮编”"""
        if any([self.country_id, self.state_id, self.city_id, self.county_id]):
            domain = []
            domain.append(('country_id', '=', self.country_id.id)) if self.country_id else domain.append(('country_id', '=', False))
            domain.append(('state_id', '=', self.state_id.id)) if self.state_id else domain.append(('state_id', '=', False))
            domain.append(('city_id', '=', self.city_id.id)) if self.city_id else domain.append(('city_id', '=', False))
            domain.extend([('county_id', '=', self.county_id.id), ('level', '=', 'county')]) if self.county_id else domain.append(('level', '=', 'city'))

            postal_code = self.env['res.postal.code'].search(domain, limit=1)
            self.postal_code_id = postal_code

    @api.onchange('postal_code_id')
    def _onchange_postal_code(self):
        """根据邮编自动填充地址信息"""
        if self.postal_code_id:
            postal_code = self.postal_code_id
            self.country_id = postal_code.country_id
            self.state_id = postal_code.state_id
            self.city_id = postal_code.city_id
            if postal_code.level == 'county':
                self.county_id = postal_code.county_id
            else:
                self.county_id = False

    @api.model_create_multi
    def create(self, vals):
        for val in vals:
            val = self._update_address_or_postal_code(val)
        return super(ResPartnerInheritForBasic, self).create(vals)

    def write(self, vals):
        vals = self._update_address_or_postal_code(vals)
        return super(ResPartnerInheritForBasic, self).write(vals)

    def _update_address_or_postal_code(self, vals):
        """根据地址更新邮编，或根据邮编更新地址"""
        # 1、检查是否提供了地址字段或邮编字段
        if any(['country_id' in vals, 'state_id' in vals, 'city_id' in vals, 'county_id' in vals]):
            # 2、根据地址字段查找并设置邮编
            domain = []
            domain.append(('country_id', '=', vals.get('country_id'))) if vals.get('country_id', False) else False
            domain.append(('state_id', '=', vals.get('state_id'))) if vals.get('state_id', False) else False
            domain.append(('city_id', '=', vals.get('city_id'))) if vals.get('city_id', False) else False
            domain.extend([('county_id', '=', vals.get('county_id')), ('level', '=', 'county')]) if vals.get('county_id', False) else domain.append(('level', '=', 'city'))

            postal_code = self.env['res.postal.code'].search(domain, limit=1)
            vals.update({'postal_code_id': postal_code.id})
        elif 'postal_code_id' in vals:
            # 3、根据邮编字段查找并设置地址
            postal_code = self.env['res.postal.code'].search([('id', '=', vals.get('postal_code_id'))])
            vals.update({'country_id': postal_code.country_id.id,
                         'state_id': postal_code.state_id.id,
                         'city_id': postal_code.city_id.id,
                         'county_id': postal_code.county_id.id if postal_code.level == 'county' else False})
        return vals

    @api.depends('country_id', 'state_id', 'city_id', 'county_id', 'street', 'postal_code_id')
    def _depends_fulfill_address_str(self):
        for s in self:
            country_name = s.country_id.name if s.country_id else ''
            state_name = s.state_id.name if s.state_id else ''
            city_name = s.city_id.name if s.city_id else ''
            county_name = s.county_id.name if s.county_id else ''
            street_name = s.street if s.street else ''
            postal_code_name = s.postal_code_id.name if s.postal_code_id else ''
            s.write({'address_str': country_name + " " + state_name + ' ' + city_name + ' ' + county_name + ' ' + street_name + ' ' + postal_code_name})

    def _get_name(self):
        name = super(ResPartnerInheritForBasic, self)._get_name()
        if self._context.get('show_chinese_address'):
            country_name = self.country_id.name if self.country_id else '\n'
            state_name = self.state_id.name if self.state_id else '\n'
            city_name = self.city_id.name if self.city_id else '\n'
            county_name = self.county_id.name if self.county_id else '\n'
            street_name = self.street if self.street else '\n'
            postal_code_name = self.postal_code_id.name if self.postal_code_id else '\n'

            name = name + "\n" + \
                   country_name + " " + state_name + ' ' + city_name + ' ' + county_name + '\n' + \
                   street_name + '\n' + \
                   postal_code_name

            name = name.replace('\n\n', '\n')
            name = name.replace('\n\n', '\n')
        elif self._context.get('show_address_inline'):
            country_name = self.country_id.name if self.country_id else ''
            state_name = self.state_id.name if self.state_id else ''
            city_name = self.city_id.name if self.city_id else ''
            county_name = self.county_id.name if self.county_id else ''
            street_name = self.street if self.street else ''
            postal_code_name = self.postal_code_id.name if self.postal_code_id else ''

            name = name + ' ' + \
                   country_name + " " + state_name + ' ' + city_name + ' ' + county_name + ' ' + street_name + ' ' + \
                   postal_code_name
        return name
